package com.grasscove.namethat;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ImageView;
import android.widget.TextView;

import com.grasscove.namethat.adapters.WordsDbAdapter;

public class HomeActivity extends Activity {
	public static final int OPTION_MENU_PLAY = 1;
	public static final int OPTION_MENU_RULES = 2;
	public static final int OPTION_MENU_ABOUT = 3;
	public static final int OPTION_MENU_SETTINGS = 4;

	public static final int DIALOG_IMPORTING_WORDLIST = 0;

	private SharedPreferences mSettings;
	
	private ImageView newGame = null;
	private ImageView settings = null;
	private ImageView about = null;
	private ImageView rules = null;

	/**
	 * Display a loading dialog and start a new thread that reads the raw
	 * file contents of the SQLite3 database and writes it to the app's
	 * data directory. This effectively installs the database without
	 * having to execute each INSERT manually.
	 * After we are done set the "worldist_installed" shared preference to true so the
	 * application can skip this step next time it starts up.
	 */
	class WordlistInstall extends AsyncTask<Void, String, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();

			showDialog(DIALOG_IMPORTING_WORDLIST);
		}

		@Override
		protected Void doInBackground(Void... unused) {

			try {

				String mDbDir = "/data/data/com.grasscove.namethat/databases/";
				new File(mDbDir).mkdirs();

				OutputStream mOutputStream = new FileOutputStream(mDbDir + WordsDbAdapter.DATABASE_NAME);
				InputStream mInputStream = getResources().openRawResource(R.raw.namethat);

				byte[] buffer = new byte[1028];
				while ( mInputStream.read(buffer) > 0 ) {
					mOutputStream.write(buffer);
				}
				mOutputStream.close();
				mInputStream.close();

			} catch (IOException e) {
				/**
				 * TODO: Actually do something with this exception.
				 */
				e.printStackTrace();
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void unused) {
			mSettings.edit().putBoolean("wordlist_installed", true).commit();
			removeDialog(DIALOG_IMPORTING_WORDLIST);
		}
	}

	/**
	 * Set the home screen view and check if the application has installed
	 * the word list.  If not, start the WordlistInstall install thread.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		mSettings = getSharedPreferences("settings", MODE_PRIVATE);
		boolean mInstalled = mSettings.getBoolean("wordlist_installed", false);

		if (mInstalled == false) {
			new WordlistInstall().execute();
		}

		ImageView newGame = (ImageView) findViewById(R.id.new_game_btn);
		newGame.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				int action = event.getAction();
				if(action == MotionEvent.ACTION_DOWN) {
					v.setBackgroundDrawable(getResources().getDrawable(R.drawable.new_game_on));
				} else if(action == MotionEvent.ACTION_UP) {
					v.setBackgroundDrawable(getResources().getDrawable(R.drawable.new_game_off));
				}
				return false;
			}
        });
		registerForContextMenu(newGame);

		ImageView settings = (ImageView)findViewById(R.id.settings_btn);
		settings.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				int action = event.getAction();
				if(action == MotionEvent.ACTION_DOWN) {
					v.setBackgroundDrawable(getResources().getDrawable(R.drawable.settings_on));
				} else if(action == MotionEvent.ACTION_UP) {
					v.setBackgroundDrawable(getResources().getDrawable(R.drawable.settings_off));
				}
				return false;
			}
        });
		registerForContextMenu(settings);

/*
		ImageView about = (ImageView)findViewById(R.id.about_btn);
		about.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				int action = event.getAction();
				if(action == MotionEvent.ACTION_DOWN) {
					v.setBackgroundDrawable(getResources().getDrawable(R.drawable.about_on));
				} else if(action == MotionEvent.ACTION_UP) {
					v.setBackgroundDrawable(getResources().getDrawable(R.drawable.about_off));
				}
				return false;
			}
        });
*/

		ImageView rules = (ImageView)findViewById(R.id.rules_btn);
		rules.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				int action = event.getAction();
				if(action == MotionEvent.ACTION_DOWN) {
					v.setBackgroundDrawable(getResources().getDrawable(R.drawable.rules_on));
				} else if(action == MotionEvent.ACTION_UP) {
					v.setBackgroundDrawable(getResources().getDrawable(R.drawable.rules_off));
				}
				return false;
			}
        });
		registerForContextMenu(rules);
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}

	public void onClickListener(View target) {
		Intent mIntent;

		switch(target.getId()) {
    		case R.id.new_game_btn:
    			mIntent = new Intent(this, CategoriesList.class);
				mIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(mIntent);
				break;
    		case R.id.settings_btn:
    			mIntent = new Intent(this, SettingsList.class);
				mIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(mIntent);
				break;
    		/*case R.id.about_btn:
    			break;*/
    		case R.id.rules_btn:
    			mIntent = new Intent(this, Rules.class);
				mIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(mIntent);
				break;
    		default:
    			break;
    	}
    }

	@Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);

        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;

        //int mSelectedCategory = info.position;

        //menu.setHeaderTitle(CATEGORIES[info.position]);
        menu.add(0, 0, 0, "Edit Wordlist");
        //menu.add(0, DELETE_CATEGORY, 2, "Delete Category");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();

        switch (item.getItemId()) {
            case 0:
                Log.v("onContextItemSelected", "worked");
                return true;
            default:
                return super.onContextItemSelected(item);
        }
    }
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, OPTION_MENU_PLAY, 1, "Play").setIcon(R.drawable.play_menu_icon);
		menu.add(0, OPTION_MENU_RULES, 2, "Rules").setIcon(R.drawable.rules_menu_icon);
		//menu.add(0, OPTION_MENU_ABOUT, 3, "About").setIcon(R.drawable.play_menu_icon);
		menu.add(0, OPTION_MENU_SETTINGS, 4, "Settings").setIcon(R.drawable.settings_menu_icon);

		return super.onCreateOptionsMenu(menu);
	}

	/**
	 * Handle the user moving to another Activity from the application menu.
	 * Set the Intent.FLAG_ACTIVITY_CLEAR_TOP flag to avoid Activity recursion.
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent mIntent;

		switch (item.getItemId()) {
			case OPTION_MENU_PLAY:
				mIntent = new Intent(this, CategoriesList.class);
				mIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(mIntent);
				break;
			case OPTION_MENU_RULES:
				mIntent = new Intent(this, Rules.class);
				mIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(mIntent);
				break;
			case OPTION_MENU_ABOUT:
				break;
			case OPTION_MENU_SETTINGS:
				mIntent =new Intent(this, SettingsList.class);
				mIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(mIntent);
				break;
			default:
				break;
		}

		return super.onOptionsItemSelected(item);
	}

	/**
	 * Create and display the loading dialog when the word list is being installed for the first time.
	 * This is only run once from the WordlistInstall thread to give a visual indication to the user
	 * the application is doing something.  This dialog cannot be canceled so the install process cannot
	 * be interrupted by the user.
	 */
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
			case DIALOG_IMPORTING_WORDLIST:
				ProgressDialog mProgressDialog;
				mProgressDialog = new ProgressDialog(this);
				mProgressDialog.setMessage("Importing word list...");
				mProgressDialog.setCancelable(false);
				mProgressDialog.show();
				return mProgressDialog;
			default:
				return null;
		}
	}
}